package com.hycc.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/*
* CAS实现自旋锁
* */
public class SpinLock {
    //Thread null
    AtomicReference<Thread> ar = new AtomicReference<>();

    //加锁
    public void myLock(){
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName()+"=> myLock");

        //自旋
        while(!ar.compareAndSet(null,thread)){

        }
    }

    //解锁
    public void myUnlock(){
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName()+"=>myUnlock");
        ar.compareAndSet(thread,null);
    }

}

class SpinLockDemo{
    public static void main(String[] args) throws InterruptedException {
        SpinLock lock = new SpinLock();

        new Thread(()->{
            try {
                lock.myLock();
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.myUnlock();
            }
        },"t1").start();

        TimeUnit.SECONDS.sleep(1);

        /*
        * t1拿到锁，t2也拿到锁
        * t1睡眠，t2自旋等待
        * t1解锁，t2解锁
        * */
        new Thread(()->{
            try {
                lock.myLock();
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.myUnlock();
            }
        },"t2").start();

    }
}